package org.jix.weblog.module.admin.event.subscriber;

import lombok.extern.slf4j.Slf4j;
import org.jix.weblog.module.admin.event.ReadArticleEvent;
import org.jix.weblog.module.common.domain.mapper.ArticleMapper;
import org.jix.weblog.module.common.domain.mapper.StatisticsArticlePVMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * @version 1.0
 * @Author Jix
 * @Date 2024/9/19 17:57
 * @注释
 */

@Component
@Slf4j
public class ReadArticleSubscriber implements ApplicationListener<ReadArticleEvent> {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private StatisticsArticlePVMapper statisticsArticlePVMapper;

    @Override
    @Async("threadPoolTaskExecutor")
    public void onApplicationEvent(ReadArticleEvent event) {
        //处理收到的事件
        Long articleId = event.getArticleId();

        //获取当前线程名
        String threadName = Thread.currentThread().getName();

        log.info("==> threadName: {}", threadName);
        log.info("==> 文章阅读事件消费成功，articleId: {}", articleId);

        // 执行文章阅读量 +1
        articleMapper.increaseReadNum(articleId);
        log.info("==> 文章阅读量 +1 操作成功，articleId: {}", articleId);

        // 当日文章 PV 访问量 +1
        LocalDate currDate = LocalDate.now();
        statisticsArticlePVMapper.increasePVCount(currDate);
        log.info("==> 当日文章 PV 访问量 +1 操作成功，date: {}", currDate);
        articleMapper.increaseReadNum(articleId);
    }
}
